<template>
  <!-- 饼图 -->
  <div class="device2-chart" ref="device2"></div>
</template>
<!-- 元素的class名字不能一样，最后将vue文件集中在一个页面中，造成class名字重复，无法使用样式 -->
<script>
import * as echarts from "echarts";

export default {
  name: "device2",
  props: {
    showdata: {
      type: Array,
      required: true,
      default: () => [],
    },
  },
  mounted() {},
  beforeUnmount() {
    if (this.device2) {
      this.device2.dispose();
    }
    window.removeEventListener("resize", this.resizeHandler);
  },
  data() {
    return {
      device2: null,
      resizeHandler: null, // 初始化 resizeHandler
      tableData: [],
    };
  },
  watch: {
    showdata: {
      handler(newData) {
        // 当 showdata 发生变化时，更新图表数据
        this.rebuildData2();
        // 确保 DOM 完全加载后再初始化 ECharts
        this.delayInitChart();
       
        console.log("Updated showdata2:", newData); // 打印更新后的数据
        console.log('tablrData2:', this.tableData);
        if (this.device2) {
          this.device1.setOption({
            series: [
              {
                data: newData, // 更新数据
              },
            ],
          });
        }
      },
      deep: true, // 深度监听
    },
  },
  methods: {
    delayInitChart() {
      // 延迟初始化 ECharts
      this.ensureDomReady().then(() => {
        this.initChart2();
      });
    },
    ensureDomReady() {
      return new Promise((resolve) => {
        const checkDom = () => {
          const chartElement = this.$refs.device2;
          if (
            chartElement &&
            chartElement.clientWidth > 0 &&
            chartElement.clientHeight > 0
          ) {
            resolve();
          } else {
            setTimeout(checkDom, 50); // 每 50ms 检查一次
          }
        };
        checkDom();
      });
    },
    initChart2() {
      this.device2 = echarts.init(this.$refs.device2);
      const chartElement = this.$refs.device2;

      if (
        !chartElement ||
        chartElement.clientWidth <= 0 ||
        chartElement.clientHeight <= 0
      ) {
        console.error("Chart element is not ready");
        return;
      }
      this.device2.setOption({
        // 'item'
        // 数据项图形触发，主要在散点图，饼图等无类目轴的图表中使用。
        // 当鼠标移动在图上时，会显示数据
        tooltip: {
          trigger: "item",
          axisPointer: {
            type: "shadow",
          },
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "value",
          boundaryGap: [0, 0.01],
        },
        yAxis: {
          type: "category",
          data: this.tableData.map((item) => item.name),
          axisTick: false,
          
        },
        series: [
          {
            name: "数量",
            type: 'bar',
            data: this.tableData.map(item => item.value),
            
          },
        ],
      });
      const resizeHandler = this.debounce(() => {
        this.device2.resize();
      }, 300);

      window.addEventListener("resize", resizeHandler);

      // 保存 resizeHandler 以便在 beforeUnmount 中移除
      this.resizeHandler = resizeHandler;
    },
    debounce(fn, delay = 1000) {
      let timer = null;
      return function (...args) {
        clearTimeout(timer);
        timer = setTimeout(() => {
          fn.apply(this, args);
        }, delay);
      };
    },

    // 重组父组件传来的数据
    rebuildData2() {
      // console.log("数据：", this.showdata);
      let stationnum = {
        value: this.showdata.length > 0 ? this.showdata[0].stationnum : 0,
        name: "站数量",
      };
      let cabinetnum = {
        value:  this.showdata.length > 0 ? this.showdata[0].cabinetnum : 0,
        name: "柜数量",
      };
      let boxnum = {
        value: this.showdata.length > 0 ? this.showdata[0].boxnum : 0,
        name: "箱数量",
      };
      let geotonenum = {
        value: this.showdata.length > 0 ? this.showdata[0].geotonenum : 0,
        name: "地调数量",
      };

      this.tableData.push(stationnum);
      this.tableData.push(cabinetnum);
      this.tableData.push(boxnum);
      this.tableData.push(geotonenum);
    },
  },
};
</script>

<style lang="scss" scoped>
.device2-chart {
  height: 100%;
  width: 100%;
}
</style>
